package com.magi.builder;

import com.magi.config.BuildingConfig;
import com.magi.config.IXmlMapperBuildingConfig;
import com.magi.core.AppUtils;
import com.magi.core.TableMetaData;

import java.util.ArrayList;

public class XmlMysqlMapperBuilder implements IXmlSQLMapperBuilder {

    private IXmlMapperBuilder builder;
    private final IDynamicSQLBuilder sqlBuilder;
    private final IXmlMapperBuildingConfig config;

    public XmlMysqlMapperBuilder(IXmlMapperBuildingConfig config) {
        this.sqlBuilder = new DynamicMysqlBuilder();
        this.config = config;
    }

    private void addSelect(String tableName, TableMetaData.Column[] columns, String parameterType, String resultType) {
        builder.addSelect("select", parameterType, resultType,
                sqlBuilder.select(tableName, columns));
    }

    private void addInsert(String tableName, TableMetaData.Column[] columns, String parameterType, String resultType) {
        builder.addInsert("insert", parameterType, resultType,
                sqlBuilder.insert(tableName, columns));
    }

    private void addDelete(String tableName, TableMetaData.Column[] columns, String parameterType, String resultType) {
        builder.addDelete("delete", parameterType, resultType,
                sqlBuilder.delete(tableName, columns));
    }

    private void addUpdate(String tableName, TableMetaData.Column[] columns, String parameterType, String resultType) {
        builder.addUpdate("update", parameterType, resultType,
                sqlBuilder.update(tableName, columns));
    }

    @Override
    public String text() {
        return builder.text();
    }

    public static void main(String[] args) {
        IXmlSQLMapperBuilder builder = new XmlMysqlMapperBuilder(new BuildingConfig());
        builder.Build(new TableMetaData("testTable", new ArrayList<TableMetaData.Column>(){
            {
                add(new TableMetaData.Column("VARCHAR", "test_col"));
            }
        }));
        System.out.println(builder.text());
    }

    @Override
    public String Build(TableMetaData metaData) {
        String tableName = metaData.getTableName();
        String pojoRef = config.getRootPojoPackageName() + "." + AppUtils.getPojoName(metaData);
        this.builder = new XmlMapperBuilder(tableName);
        TableMetaData.Column[] columns = metaData.getColumns();
        this.addDelete(tableName,
                columns,
                pojoRef,
                null);

        this.addInsert(tableName,
                columns,
                pojoRef,
                null);

        this.addUpdate(tableName,
                columns,
                pojoRef,
                null);

        this.addSelect(tableName,
                columns,
                pojoRef,
                pojoRef);

        return this.builder.text();
    }
}
